package com.example.ecas.service;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.models.*;
import com.aliyun.sdk.service.dysmsapi20170525.*;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

@Repository
@Service
public interface SmsService {

    // 生成四位随机验证码
    static int createRandomCode() {
        return (int) Math.round(Math.random() * 8999 + 1000);
    }

    // 向指定手机号发送随机短信验证码，返回发送的验证码
    static int sendSms(String phone) throws Exception {

        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId("LTAI5tQ41YhjEAotx8WAg4Tg")
                .accessKeySecret("LA6CaYwkIMeF7IyMoInRKECcuSoPKo")
                .build());

        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou")
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();

        int code = createRandomCode();

        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName("ECAS")
                .templateCode("SMS_461845548")
                .phoneNumbers(phone)
                .templateParam("{\"code\":\"" + code +"\"}")
                .build();

        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        SendSmsResponse resp = response.get();
        System.out.println(new Gson().toJson(resp));

        client.close();
        return code;

    }
}
